<script lang="ts" setup>
import Motion from "./utils/motion";
import { loginRules } from "./utils/rule";
import TypeIt from "@/components/TypeIt/index";
import { initRouter } from "@/router/utils";
import { useNav } from "@/layout/hooks/useNav";
import { ElLoading, ElMessage, type FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/stores/modules/user";
import { useKBStoreHook } from "@/stores/modules/KB";
import { bg, illustration, loginDetector } from "./utils/static";
import { ImageVerifyCmp } from "@/components/ImageVerify/index";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

import $md5 from "js-md5";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import Tenant from "@iconify-icons/ri/group-2-fill";

defineOptions({
  name: "Login",
});

const imgCode = ref("");
const router = useRouter();
const loading = ref(false);
const checked = ref(false);
const ruleFormRef = ref<FormInstance>();
const currentPage = computed(() => {
  return useUserStoreHook().currentPage;
});

const { initStorage } = useLayout();
initStorage();
const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "admin",
  password: "admin",
  // password: "sy123456",
  tenantId: "000000",
  // username: "yuyanglin",
  // password: "tc123456",
  verifyCode: "",
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const fullLoading = ElLoading.service({
        lock: true,
        text: "登录中,请稍后。。。",
        spinner: "el-icon-loading",
      });
      useUserStoreHook()
        .loginByUsername({
          username: ruleForm.username,
          password: $md5(ruleForm.password),
          // code: ruleForm.verifyCode,
          tenantId: ruleForm.tenantId,
        })
        .then((res) => {
          if (res) {
            useKBStoreHook().fetchTyperel();
            useKBStoreHook().fetchTags();
            // 获取后端路由
            initRouter().then(() => {
              // router.push("/");
              ElMessage.success("登录成功");
            });
          }
        })
        .finally(() => {
          fullLoading.close();
          loading.value = false;
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});

watch(imgCode, (value) => {
  useUserStoreHook().SET_VERIFYCODE(value);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        inline-prompt
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(loginDetector)" height="380" width="800" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <!-- <avatar class="avatar" /> -->
          <Motion>
            <h2 class="outline-none">
              <TypeIt :cursor="false" :speed="150" :values="[title]" />
            </h2>
          </Motion>

          <el-form
            v-if="currentPage === 0"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <!-- <Motion :delay="80">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入租户ID',
                    trigger: 'blur',
                  },
                ]"
                prop=""
              >
                <el-input
                  clearable
                  v-model="ruleForm.tenantId"
                  placeholder="租户ID"
                  :prefix-icon="useRenderIcon(Tenant)"
                />
              </el-form-item>
            </Motion> -->
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur',
                  },
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  :prefix-icon="useRenderIcon(User)"
                  clearable
                  placeholder="账号"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  :prefix-icon="useRenderIcon(Lock)"
                  clearable
                  placeholder="密码"
                  show-password
                />
              </el-form-item>
            </Motion>

            <!-- <Motion :delay="200">
              <el-form-item prop="verifyCode">
                <el-input
                  clearable
                  v-model="ruleForm.verifyCode"
                  placeholder="验证码"
                  :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                >
                  <template v-slot:append>
                    <ImageVerifyCmp v-model:code="imgCode" />
                  </template>
                </el-input>
              </el-form-item>
            </Motion> -->

            <Motion :delay="250">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-between items-center">
                  <el-checkbox v-model="checked">
                    {{ "记住密码" }}
                  </el-checkbox>
                  <!-- <el-button
                    link
                    type="primary"
                    @click="useUserStoreHook().SET_CURRENTPAGE(4)"
                  >
                    {{ t("login.forget") }}
                  </el-button> -->
                </div>
                <el-button
                  :loading="loading"
                  class="w-full mt-4"
                  size="default"
                  type="primary"
                  @click="onLogin(ruleFormRef)"
                >
                  {{ "登录" }}
                </el-button>
              </el-form-item>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@/styles/login.css";
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
